<template>
  <!-- 登录模态框 -->
  <div class="modal">
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登录框 -->
    <div class="loginbox">
      <!-- 关闭按钮 -->
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <!-- 切换导航 -->
      <section class="nav">
        <a
          href="#"
          :class="{ active: isShowContent }"
          @click="isShowContent = true"
          >手机号登录</a
        >
        |
        <a href="#" :class="{ active: !isShowContent }" @click="showQrCode"
          >微信扫码登录</a
        >
      </section>
      <!-- 导航对应的内容区域 -->
      <div class="content">
        <!-- 手机登录 -->
        <div class="phonelogin" v-show="isShowContent">
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入手机号"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入短信验证码"
              v-model="code"
            />
            <button class="btn btncode" @click="getCode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="btn btncode" v-show="isShowCount">
              {{ `${count}s` }}
            </button>
          </div>
          <div class="row">
            <button class="btn btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 二维码登录 -->
        <!-- 微信二维码生成：二：给显示二维码容器添加一个id -->
        <div id="weixin" class="qrcode" v-show="!isShowContent">微信登录</div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations } from "vuex";
import {
  SendSMSAPI,
  PhoneLoginAPI,
  BindPhoneAPI,
  UserProfilesAPI,
} from "@/request/api";
import { validatePhoneNumber } from "@/utils";
export default {
  data() {
    return {
      isShowContent: true,
      //滑块提示信息
      msg: "向右滑动",
      phoneNumber: "17628326441",
      // 倒计时
      count: 59,
      //是否显示倒计时数字
      isShowCount: false,
      //验证码
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      chanIsLogined: "loginStatus/chanIsLogined",
      chanIsShowToast: "showToast/chanIsShowToast",
    }),
    ...mapActions({
      asyncIsShowToast: "showToast/asyncIsShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    //倒计时方法
    countdown() {
      this.isShowCount = true;
      let times = setInterval(() => {
        this.count--; //递减
        if (this.count == 0) {
          clearInterval(times);
          //显示 获取验证码
          this.isShowCount = false;
          //初始化count
          this.count = 59;
        }
      }, 1000);
    },
    //提取手机号和滑块验证
    toVerity() {
      //手机输入正确（不为空，格式正确），不正确 return
      //正则验证 reg.test(string) 成功 返回true 都不匹配返回false
      //工具函数（传入手机号） 返回 是成功 true 还是失败false
      if (!validatePhoneNumber(this.phoneNumber)) {
        // alert("请输入正确的手机号");
        // this.$refs.phone.focus();
        // this.chanIsShowToast({
        //   isShow: true, //是否显示提示
        //   msg: "请输入正确的手机号码",
        //   type: "danger", //提示图标类型
        // });
        // setTimeout(() => {
        //   this.chanIsShowToast({ isShow: false });
        // }, 1500);
        this.asyncIsShowToast({
          msg: "请输入正确的手机号码",
          type: "danger", //提示图标类型
        });
        return false;
      }
      // 2、滑块验证码 需要正确 不正确return
      //如果是向右滑动 或者是 再试一次 都是表示有不成功
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        // alert("请先进行滑块验证");
        this.asyncIsShowToast({
          msg: "请先进行滑块验证",
          type: "danger", //提示图标类型
        });
        return false;
      }
      return true;
    },
    //获取验证码
    async getCode() {
      if (!this.toVerity()) return;
      //3.获取验证码功能（给后台发起一个请求），发送成功后还有一个倒计时的效果59s..

      //发请求
      let res = await SendSMSAPI({
        phone: this.phoneNumber.trim(),
      });

      console.log("发送结果", res);
      //如果res为false 直接return
      if (!res) return;
      if (res.code == 0) {
        // alert("短信验证码发送成功");
        this.asyncIsShowToast({
          msg: "短信验证码发送成功",
          type: "success", //提示图标类型
        });
        //倒计时（循环interval递减数字count）
        this.countdown();
      }
    },
    //登录
    async submitFn() {
      //1.手机输入正确（不为空，格式正确），不正确 return
      //2.滑块验证码 需要正确 不正确return
      if (!this.toVerity()) return;
      //3.输入了短信验证码（前端没有拿到手机获取到的验证码）
      if (this.code.trim() === "") {
        this.asyncIsShowToast({
          msg: "请输入验证码",
          type: "danger", //提示图标类型
        });
        return;
      }
      //4.发起登录请求
      let uuid = localStorage.getItem("uuid");

      let res = null;
      if (uuid) {
        res = await BindPhoneAPI({
          verifyCode: this.code.trim(),
          phone: this.phoneNumber.trim(),
          uuid,
        });
      } else {
        res = await PhoneLoginAPI({
          verifyCode: this.code.trim(),
          phone: this.phoneNumber.trim(),
        });
      }

      if (!res) return;

      // console.log("登录成功", res);
      //1.提示登录成功
      this.asyncIsShowToast({
        msg: "登录成功",
        type: "success", //提示图标类型
      });
      // 2、存储token
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 3、隐藏登录模态窗口
      this.changeIsShowLoginModal(false);
      // 4， 登录状态切换
      this.chanIsLogined(true);
      //5.删除uuid
      localStorage.removeItem("uuid");

      //6.清除地址栏的code

      this.$router.push(this.$route.path);
      //7.登录成功后，读取用户信息
      // let uRes = await UserProfilesAPI();
      // console.log("用户信息:", uRes);
      this.asyncChangeUserInfo();
    },
    //微信二维码生成：显示二维码
    showQrCode() {
      this.isShowContent = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICBkaXNwbGF5OiBub25lOw0KfQ0K",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginbox {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      right: 50px;
      top: 10px;
      width: 22px;
      height: 22px;
      background: url("../assets/img/close.png");
    }
    .nav {
      display: flex;
      justify-content: center;
      padding-top: 50px;
      font-size: 20px;
      a {
        text-decoration: none;
        color: #9b9ab3;
        padding: 0 10px;
        &.active {
          color: #030303;
        }
      }
    }
    .content {
      width: 355px;
      margin: 20px auto 0;
      height: 200px;
      .phonelogin {
        .row {
          display: flex;
          margin-bottom: 20px;
        }
        .ipt {
          outline: none;
          flex: 1;
          height: 48px;
          padding-left: 10px;
        }
        .btn {
          border: none;
          cursor: pointer;
          line-height: 48px;
        }
        .btncode {
          margin-left: 10px;
          width: 100px;
        }
        .btnlogin {
          color: #fff;
          width: 100%;
          background-color: #0a328e;
        }
      }
      #weixin {
        /* background-color: #fcf; */
        display: flex;
        justify-content: center;
        margin-top: -20px;
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>
